package com.mrper.util;

import android.annotation.SuppressLint;
import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Process;
import android.support.annotation.ColorRes;
import android.support.annotation.DrawableRes;
import android.util.Log;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.Enumeration;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

/**
 * Created by admin on 2016/3/8.
 * 与Apk相关的辅助方法
 */
@SuppressWarnings("all")
public class ApkUtil {

    /**
     * 获取状态栏高度
     **/
    public static int getStatusBarHeight(Context context) {
        Class<?> c = null;
        Object obj = null;
        Field field = null;
        int x = 0;
        try {
            c = Class.forName("com.android.internal.R$dimen");
            obj = c.newInstance();
            field = c.getField("status_bar_height");
            x = Integer.parseInt(field.get(obj).toString());
            return context.getResources().getDimensionPixelSize(x);
        } catch (Exception e1) {
            Log.d("MainActivity", "get status bar height fail");
            e1.printStackTrace();
            return 75;
        }
    }

    /**
     * 获取打包渠道名称,在360加固后，该apk包中的渠道文件遗失，不适用
     *
     * @param context 上下文对象
     * @return 打包渠道名称
     */
    @Deprecated
    public static String getChannelName(Context context) {
        ApplicationInfo appinfo = context.getApplicationInfo();
        String sourceDir = appinfo.sourceDir;
        String ret = "";
        ZipFile zipfile = null;
        try {
            zipfile = new ZipFile(sourceDir);
            Enumeration<?> entries = zipfile.entries();
            while (entries.hasMoreElements()) {
                ZipEntry entry = ((ZipEntry) entries.nextElement());
                String entryName = entry.getName();
                System.out.println("文件名>>>---------->>>>> entryName: " + entryName);
                if (entryName.contains("meguochannel@")) {
                    ret = entryName;
                    break;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (zipfile != null) {
                try {
                    zipfile.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        String[] split = ret.split("@");
        if (split != null && split.length >= 2) {
            return ret.substring(split[0].length() + 1);

        } else {
            return "";
        }
    }

    /**
     * 通过颜色资源ID获取颜色值，兼容Android M
     *
     * @param context
     * @param id
     * @return
     */
    public static int getColorById(Context context, @ColorRes int id) {
        return context.getResources().getColor(id);
    }

    /**
     * 通过ID获取图片资源,兼容Android L/M
     *
     * @param context
     * @param id
     * @return
     */
    @SuppressWarnings("deprecation")
    @SuppressLint("deprecation")
    public static Drawable getDrawableById(Context context, @DrawableRes int id) {
        return context.getResources().getDrawable(id);
    }

    /**
     * 获取资源ID
     *
     * @param context
     * @param defType 在xml中定义的类型，如果是字符串则是String，如果是整数则是Integer...etc.
     * @param defName 在xml中定义的名称
     * @return
     */
    public static int getResourceId(Context context, String defType, String defName) {
        return context.getResources().getIdentifier(defName, defType, context.getPackageName());
    }

    /**
     * 获取程序的版本号，获取失败返回空字符串
     *
     * @param context
     * @return
     */
    public static String getVersionName(Context context) {
        try {
            return context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionName;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }


    /**
     * 获取软件版本值
     *
     * @param context
     * @return
     */
    public static int getVersionCode(Context context) {
        try {
            return context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionCode;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return -1;
    }

    /**
     * 安装Apk程序
     *
     * @param context
     * @param filename
     */
    public static void installApk(Context context, String filename) {
        Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
        intent.setDataAndType(Uri.fromFile(new File(filename)), "application/vnd.android.package-archive");
        context.startActivity(intent);
    }

    /**
     * 卸载Apk程序
     *
     * @param context
     * @param packagename
     */
    public static void uninstallApk(Context context, String packagename) {
        context.startActivity(new Intent(Intent.ACTION_DELETE, Uri.parse("package:" + packagename)));
    }

    /**
     * 获取应用的进程名称
     *
     * @param cxt 上下文对象
     * @param pid see {@link Process#myUid()}
     * @return null may be returned if the specified process not found
     */
    public static String getProcessName(Context cxt, int pid) {
        ActivityManager am = (ActivityManager) cxt.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningAppProcessInfo> runningApps = am.getRunningAppProcesses();
        if (runningApps == null) {
            return null;
        }
        for (ActivityManager.RunningAppProcessInfo procInfo : runningApps) {
            if (procInfo.pid == pid) {
                return procInfo.processName;
            }
        }
        return null;
    }

}
